package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Commodity;
import cn.wolfcode.trip.base.query.CommodityQueryObject;
import cn.wolfcode.trip.base.service.ICommodityCatalogService;
import cn.wolfcode.trip.base.service.ICommodityService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("commodity")
public class CommodityController {

    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private ICommodityCatalogService commodityCatalogService;
    @RequestMapping("list")
    public String list(@ModelAttribute("qo") CommodityQueryObject qo, Model model){
        model.addAttribute("commodityCatalogs",commodityCatalogService.list());
        model.addAttribute("pageInfo",commodityService.query(qo));
        return "commodity/list";
    }

    @RequestMapping("delete")
    @ResponseBody
    public JSONResult delete(Long id){
        commodityService.delete(id);
        return new JSONResult();
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(MultipartFile file , Commodity commodity) {
        JSONResult jsonResult = new JSONResult();
        if (file!=null&&file.getSize()>0){
            String upload = UploadUtil.upload(file, UploadUtil.PATH + "/upload");
            commodity.setPicture(upload);
        }
        try{
            commodityService.saveOrUpdate(commodity);
        }catch (Exception e){
            return jsonResult.mark(e.getMessage());
        }
        return jsonResult; //象征性返回操作成功
    }
}
